\documentclass[11pt,oneside]{report}
\usepackage{graphicx}
\usepackage{epstopdf}
\usepackage[letterpaper]{geometry}
\usepackage{amsmath}
\usepackage{titlesec}
\usepackage{fullpage}
\usepackage{setspace}
\usepackage{bold-extra}
\usepackage{tocloft}
\usepackage{url}
%\usepackage{apacite}
\usepackage{fancyhdr}
\usepackage[free-standing-units]{siunitx}
\usepackage{multirow}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{booktabs}
\usepackage{array}
\usepackage{listings}

\newcommand{\chapterStyle}{\LARGE\bfseries\scshape\centering}

\titleformat{\chapter}[hang]{\chapterStyle}{\thechapter.0}{1em}{}
\titlespacing{\chapter}{0em}{-5em}{0em}

\titleformat{\section}[hang]{\Large\scshape\bfseries}{\thesection}{1em}{}

%\titleformat{\section}[hang]{\large\bfseries}{\thechapter.0}{1em}{}

% prevents TOC from resetting page numberings
\let\oldsetcounter=\setcounter
\renewcommand\setcounter[2]{%
    \def\arg{#1}\def\pg{page}%
    \ifx\arg\pg\else\oldsetcounter{#1}{#2}\fi}
		
\renewcommand{\cfttoctitlefont}{\hfill\chapterStyle}
\renewcommand{\cftaftertoctitle}{\hfill}
\renewcommand{\cftloftitlefont}{\hfill\chapterStyle}
\renewcommand{\cftafterloftitle}{\hfill}
\renewcommand{\cftlottitlefont}{\hfill\chapterStyle}
\renewcommand{\cftafterlottitle}{\hfill}

\renewcommand\listfigurename{\centering List Of Figures}
\renewcommand\listtablename{\centering List Of Tables}
\renewcommand{\contentsname}{\centering Contents}
\renewcommand\bibname{References}

\newcommand{\docSpacing}{1.6}

%file, caption, label, scaling
\newcommand{\picfigure}[4]{\begin{figure}\begin{center}\includegraphics[scale = #4]{#1}\caption{#2}\label{#3}\end{center}\end{figure}}

%partial derivative
\newcommand{\partiald}[2]{\frac{\partial #1}{\partial #2}}

\setlength{\headheight}{15pt}

\begin{document}

\newpage
\pagestyle{plain}
\pagenumbering{roman}
\setcounter{page}{0}

%\title{Oculus Rift}
%\author
%{
%Wei Tai \\
%James Liu \\
%Kelvin Ritland \\
%Rey Zeng \\\\
%EECE 284
%}
%\date{\today}
%\maketitle
\input{./Title_Page.tex}

\setstretch{\docSpacing}

%\begin{abstract}
%  \thispagestyle{plain}
%  \addcontentsline{toc}{chapter}{Abstract}
%   Abstract

%\end{abstract}

\setstretch{1}
\quad\\[-6em]
\tableofcontents
\newpage
\quad\\[-6em]
\listoffigures
\listoftables
\addcontentsline{toc}{chapter}{List of Figures}
\addcontentsline{toc}{chapter}{List of Tables}

\newpage
\setstretch{\docSpacing}

\thispagestyle{fancy} % page number styling/formatting
\pagestyle{fancy}
\fancyhead{}
\fancyhead[R]{\thepage}
\fancyfoot{}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}

%reduces excessive whitespace around equations
\setlength{\abovedisplayskip}{1pt}
\setlength{\belowdisplayskip}{1pt}
\setlength{\abovedisplayshortskip}{1pt}
\setlength{\belowdisplayshortskip}{1pt}

\setcounter{page}{1}
\pagenumbering{arabic}
\chapter{Introduction}
The purpose of this project was to design and create the fastest battery-powered rover which would follow a wire with an alternating current. There were also turning and stopping signals, indicated by a number of perpendicular wires on the track that the robot must read to navigate successfully (2 for left turns, 3 for right turns, and 4 for starting/stopping) \cite{instructions}.

The design approach internally was very modular. The robot was had two main wheels, powered by separate motors at the back, with a ball caster support in front. Each of the components was tested separately before being added together to form a working rover. This process limited the possibility of errors and made debugging easier. 

\begin{figure}[h]
\centering
\includegraphics[width=8cm]{Hardware_Block2.pdf}
\caption{Block diagram of hardware functions}
\label{fig:hardwareblock}
\end{figure}
\begin{figure}
\centering
\includegraphics[width=14cm]{Software_Block.pdf}
\caption{Block diagram of software functions}
\label{fig:softwareblock}
\end{figure} \vspace{-1.5em}
The hardware block diagram is shown in Figure \ref{fig:hardwareblock}. Inductors were used to detect magnetic fields generated by the wire, which was amplified before being sent into the microcontroller. The motor circuit used a simple MOSFET circuit, and the power rails provided stable voltage to all the electrical components. Each block is described in greater detail in the electronics section. 

The software design is shown in Figure \ref{fig:softwareblock}. The software took processed input from the circuit and used a PID algorithm to line follow. A finite state machine was used to detect various events. Interfacing was necessary to input the signal from the inductor and output information onto the display (LCD). The timer utilizes a periodic interrupt to provide delays necessary in the software. The solid-lined boxes corresponds to sections in the Software chapter that describes the module in greater detail. The actual C program is in the Appendix. 

\chapter{Electronics}
The rover had four electronic modules: the track signal detection and amplifying module, the control module, the motor module, and the power rail module. They worked together to process and transmit electronic signals that the rover's navigation relied upon. All components except three inductors were soldered on one PCB board instead on a breadboard to reduce mass.

\section{Signal Detection and Amplification Module}
\begin{figure}[h]
\center
\includegraphics[width=0.8\columnwidth]{Filter_Circuit.pdf}
\caption{Schematic diagram of the signal detection and amplification module.}
\label{fig:sensor}
\end{figure}
The purpose of the signal detection and amplification module, shown in Figure \ref{fig:sensor}, was to detect the 20 V$_{\text{pp}}$, 15.175 kHz sinusoidal signal in the wires marking the rover track \cite{instructions}. The first stage of the module consisted of a parallel inductor-capacitor (LC) network, with inductance and capacitance chosen to be 1 mH and 0.1 $\mu$F so that the network resonated near 15.175 kHz. The signal across the parallel network was then amplified by an inverting amplifier with a gain of about 20 (gain based on initial testing). The amplified signal was then rectified, using a capacitor and resistor. The capacitor and resistor values in this stage had a time constant of 0.1 ms, which matched the period of the target signal, thus kept the output of the modules as close to DC as possible at that particular frequency. 

The rover had three of these modules. Two of the modules' inductors were placed perpendicular to the rover's direction of travel, one on the right and the other on the left. The rover's PID algorithm (see Section \ref{sec:PID}) operated based on these two modules. The third module's inductor was placed perpendicular to the rover's direction of travel to detect turning signals, which serves as the basis of the rover's event detection system. All three module's amplification stages were realized around a single LM324 IC, which houses four operational amplifiers.

\section{Control Module}
The control module was constructed around a P89LPC9351 microcontroller. It stored and executed all the software of the rover. Three analog inputs were used to accept output from the inductor sensors, and a fourth analog input connected to a resistor voltage divider was used to monitor the power rail dedicated to the rover's motors. The control module had a USB adapter for software upload purpose. The control module also used a LCD to display rover run time, and debugging information during testing.

\section{Motor Module}
\begin{figure}[h]
\center
\includegraphics[width=0.4\columnwidth]{Motor_MOSFET.pdf}
\caption{Schematic diagram of one motor control circuit.}
\label{fig:motor}
\end{figure}
The motor control module is shown in Figure \ref{fig:motor}, which is essentially an NMOSFET gate. Each drove a motor based on a pulse width modulated signal (PWM) from the microcontroller. The gate of the NMOSFET was connected to a digital output of the microcontroller, where the PWM was generated, and a pull up resistor. The drain terminal of the module was connected to the motor and a 6 V battery terminal. The rover had two motor control modules, one for each motor driving the left and right wheel.

\section {Power Rail Module}
\begin{figure}[h]
\center
\includegraphics[width=0.5\columnwidth]{Power_Rail.pdf}
\caption{Schematic diagram of the power rail module providing the $\pm 4.5$ V and common ground rail.}
\label{fig:power}
\end{figure}

The power rail module provided all the voltage levels needed by the electronics. The rover electronics required four voltage rails, a common ground, a $+4.5$ V rail, a $-4.5$ V rail, and a +6 V rail. The available power source was a 9 V alkaline battery and a 6 V DC source consisting of 4 AA batteries connected in series. To realize the $\pm$4.5 V rails and the common ground, a voltage divider was constructed out of two 100 k$\Omega$ resistors connected in series to the 9 V battery, and a operation amplifier buffer. The buffer's output voltage served as the common ground, while the terminal voltages of the voltage dividers served as the $\pm$4.5 V rails. This circuit is shown in Figure Figure \ref{fig:power}. The 6 V rail was realized by connecting the negative terminal of the 6 V source to the common ground. The $\pm$4.5 power rails drove all electronics except the motors. The motors required higher voltage, so the 6 V rail was dedicated to power the motors.


\chapter{Software}
The main components of the software were the timer, the sensor readings, the LCD, the PID system, and the overall event system. Much of the code that interfaced with the microcontroller or LCD came from examples provided or the respective user manuals.

\section{Timer}
The file \texttt{timer.h} (see Section \ref{source:timer}) tracked time for the system. This feature had many uses, from counting the overall driving time displayed on the LCD, to generating delays for the system. The total time of the system was stored in the variable \texttt{millis} which was reset in the function \texttt{InitClock()}. The program utilized the microcontroller's built-in countdown timer to generate an interrupt every 0.1 ms, calling the function \texttt{timerupdate()}, which increments the time variable \texttt{millis} every 10 calls, on which system delays were based. The constant \texttt{XTAL}, used to reload the microcontroller's internal timer, was calibrated and tested with external time tracking device.

As well, the timer controlled the PWM output, by keeping track of the number calls to the \texttt{timerupdate()} function modulo 100. If the motor speed (which is a number between 0 and 100) is greater than the number of calls, the output the motor is turned on.

%\section{Sensor Measurements (ADC)}
%The file \texttt{adc.h} (in Section \ref{source:adc}) provided a wrapper around interfacing with the analog inputs to the microcontroller. 
%The \texttt{InitADC()} function initialized the ports (0.1, 0.2, 0.3, and 0.4) to input mode and set up their values to be continuously read into \texttt{AD1DAT0} to \texttt{AD1DAT3}. 
%Then, a simple call to \texttt{getAnalog()} returned the reading from the specified port. 
%The constants \texttt{LEFT\_SENSOR}, \texttt{RIGHT\_SENSOR}, \texttt{MID\_SENSOR}, and \texttt{BATTERY\_SENSOR} (in \texttt{configuration.h}) were used to keep track of which sensor was connected to which port for ease of use.

\section{LCD}
The file \texttt{lch.h} (reproduced in Section \ref{source:lcd}) contained code that provides an interface to the LCD. 
The main functions in the code were to initialize the LCD (\texttt{initLCD()}), send a command to the LCD (\texttt{lcdCommand()}), and write a character to the LCD (\texttt{lcdWrite()}). 
The write and command functions worked by writing the data the LCD port, setting appropriate flags, and then causing a falling edge on the enable signal,
which caused the LCD to process the character or command. 
The initialization function sent a sequence of commands to wake up the LCD and set the LCD in correct mode.

There were also some utility functions for the LCD. 
\texttt{lcdClear()} cleared the LCD of all text. 
\texttt{setLcdCursor()} and \texttt{setLcdHome()} moved where the next character will be written. 
Finally, \texttt{writeString()} wrote a string to the display by sending characters one by one (via \texttt{lcdWrite()}), 
and \texttt{writeNum()} wrote a number to the display by building a string corresponding to the number and using \texttt{writeString()}.

The LCD was used in \texttt{main.c} (Section \ref{source:main}) to write debug values (the sensor readings, the motor speeds) 
as well as the time elapsed since passing the start and the battery voltages. 
Every 100 cycles of the main loop (about 100 ms), 
the LCD was cleared and refreshed with new readings using the functions previously described.

\section{PID}\label{sec:PID}
The file \texttt{pid.h}, reproduced in Section \ref{source:pid}, provided the core instructions that controlled the general movement of the robot as it navigated along the track. First, the system derived a normalized error value that represented the deviation of the robot from the path based on the signals picked up by the inductors in \texttt{getError()}. The error function used was
\begin{align*}
E = \frac{I_l - I_r}{I_l+I_r}
\end{align*}
where $I_l$ and $I_r$ are the left and right inductor readings. If both readings were too low, the error was set to 1 or $-1$ based on last error observed.
 Then, the system adjusted the left and right motor speeds as necessary to get the robot back on track based on the errors calculated using \texttt{getPIDAdjustment()}, using proportional (based on the error magnitude) and derivative (based on the change in error) gains. Lastly, \texttt{pidUpdate()} finalized the motors' speed to be used until the next invocation to the PID system. %Refer to Fig \ref{fig:pid} for overview. 
%\begin{figure}
%\center
%\includegraphics[width=0.4\columnwidth]{pid}
%\caption{Overview of PID system.}
%\label{fig:pid}
%\end{figure}

%From our understanding, our PID system is superior to that employed by most teams as it derives a continuous error that allows precise speed adjustments. Normally, the error value of PID system is quantized such that system is limited to handling around five error levels. As a result, the turning can be difficult to tune and code more verbose. In contrast, our system provides us with the option to extract error to an arbitrary precision, limited only by the inductor signal resolution and word size of the micro-controller. In short, it is very robust and optimized.

\section{Event Detection and State Control}
The event detection system was built around a finite state machine model. 
State transitions to other states typically occured when the robot passes over the cross signals in the track, 
which was detected by the function \texttt{crossDetection()} 
(see Section \ref{source:eventDetection} for implementation). 
This function, intended to be continually called, worked by monitoring the status of the middle inductor in a static variable. 
If the signal rose above a threshold with the previous signal below the threshold, 
the function returned true, 
indicating the robot has crossed a perpendicular wire (otherwise it returns false). 
The function then entered a `debounce' period for 80 calls (about 80 ms),
 where it was insensitive to any other rising edges for a period of time, 
preventing other spurious rising edges from being detected due to noise.


\begin{figure}
\center
\includegraphics[width=0.64\columnwidth]{fsm}
\caption{The finite state machine model used in the code}
\label{fig:fsm}
\end{figure}

The cross signals were normally counted by using a countdown timer. 
Each cross signal given by \texttt{crossDetection()} incremented a counter variable and reloads a timer.
When that timer returned to 0, the counter variable indicated the number of lines crossed.


The states and transition conditions are shown in Figure \ref{fig:fsm}. 
The code implementing these state transitions was split between \texttt{main.c} and \texttt{eventDetection.h}, 
reproduced in Sections \ref{source:main} and \ref{source:eventDetection} respectively. 
The robot in normal operation was usually in the `straight' state, where it was simply using PID control to follow the wire. 
When it crossed a certain number of lines, it went into the `left', `right' or `start' states, as shown in Figure \ref{fig:fsm}. 
In the `left' and `right' states, the robot continued to follow the wire. 
However, an additional line crossing would cause a left or right turn to be executed for a timed duration, 
after which the robot returned to the `straight' state. 
In the `start' state, the robot would either reset the counter that times the robot, 
or stop itself if it has already been in the `start' state before.

\chapter{Evaluation}

\section{Testing}
Each component of the robot (hardware and software) first was tested individually to ensure proper functioning. Afterward, the robot was placed on the track and and the overall parameters were tuned, and reliability was tested. The trials are shown in Table \ref{table:tuning}. The robot had a time of 74.62 s on the demonstration day.

\begin{table}[h]
\begin{center}
\caption{Tuning the robot (March 10, 2014)}
\begin{tabular}{llllll}\toprule
\parbox{2cm}{Proportional Gain} & \parbox{1.5cm}{Derivative Gain}  & \parbox{1cm}{Event Timer} & \parbox{2cm}{Debounce Period} & \parbox{2cm}{Reading Threshold} & Comment\\\midrule
8 & 1 & 500 & 10  & 5 & Trouble with right turn\\
8 & 1 & 500 & 100 & 5 & Wandered off before finish line\\
5 & 1 & 500	& 100 & 5 & Could not follow sharp turn\\
5 & 1 & 500 & 100 & 10 & Smooth run, $\sim$80 s run time\\
5 & 1 & 500 & 100 & 10 & Smooth run, $\sim$80 s run time\\\bottomrule
\end{tabular}
\label{table:tuning}
\end{center}
\end{table}
In an attempt to speed the robot up, it was modified to ignore errors before a particular threshold and instead go straight. However, testing was unable to yield a suitable threshold without the robot wandering off the track.

\section{Strengths}
\textbf{\textsc{Performance}} \\
Robot was reasonably fast when working properly. \\
\textbf{\textsc{Design}} \\
Simply design, easy to debug. \\
Analog PID controller allowed for precise control of turning. \\
Inductors were positioned as far away from the rotation axis as possible, allowing higher resolution for inductor readings for finer turning control. \\
\textbf{\textsc{Team Organization}} \\
Finished early. Had a working robot during the week of spring break. \\
Documentations of robot parts were well-organized. \\
Once-a-week meetings were consistent. 
\section{Weaknesses}
Despite the good result on competition day, the robot has several weaknesses that could have been improved. \\
\textbf{\textsc{Quality}} \\
Poor overall build quality, with the soldering of circuit particularly unreliable. There were several times where connections terminated unexpectedly (once during the demonstration). \\
Chassis was heavy in comparison with that of more optimized robots. \\
\textbf{\textsc{Inductors}} \\
Inductor gain was too low, making it difficult to identify signals from noise. \\
Relied on tape to hold inductors in place, making inductors readings inconsistent over time due to shifting\\

These weakness could have been overcome by spending time to design the robot and thinking about possible pros and cons, instead of jumping straight into the tasks. The build quality would improve if more care was taken during the construction (eg. soldering slowly and carefully).

\chapter{Conclusion}
Overall, the robot read the magnetic field from the wire via an inductor circuit into the microcontroller, processed the signal using PID control, and subsequently adjusted the power to the motors to stay on course. The robot also was able to respond to the left and right turn signals on the track. The robot achieved a time of 74.62 s, which was the third best time of 16 groups.

For about 30 hours over the past 4 months, we tried our best to build the best robot possible. We faced troubles including lack of tools, faulty oscilloscopes, and static electricity burning out an LCD. Despite the team's lacking of experience in mechanical design, we managed to put together a working robot in a short period of time. On the competition day, our robot successfully completed its mission with competitive timing. The team is very satisfied with its performance. 

Through this experience, we discovered that to construct the best robot, a team needs to be creative and take advantage of any resource available to achieve the goal. Ample time must be dedicated to design. Keeping the team updated on latest changes through discussion is also key to keeping the team motivated. Overall, we constructed the best robot possible given the time and resources available. Hopefully this is a valuable learning experience that we will never forget.
\thispagestyle{fancy}

\raggedright
\bibliographystyle{plain} 
\bibliography{refs}
\addcontentsline{toc}{chapter}{References}

\thispagestyle{fancy}
\chapter*{Bibliography}
\addcontentsline{toc}{chapter}{Bibliography}
\begin{itemize}
\item Newhaven Display International Inc., Character Liquid Crystal Display Module, Elgin IL, 2011. \url{http://datasheet.octopart.com/NHD-0216BZ-FL-YBW-Newhaven-Display-datasheet-13225160.pdf}
\item NXP Semiconductors, P89LPC9331/9341/9351/9361 User manual, 2009. \url{http://www.nxp.com/documents/user_manual/UM10308.pdf}
\item NXP Semiconductors, P89LPC9331/9341/9351/9361 data sheet, 2009. \url{http://www.nxp.com/documents/data_sheet/P89LPC9331_9341_9351_9361.pdf}
\end{itemize}

\titleformat{\chapter} {\chapterStyle}{Appendix \thechapter\quad}{0em}{}
\setstretch{1}
\appendix
\chapter{Microcontroller Code} 
\lstset{ %
  basicstyle=\scriptsize,        % the size of the fonts that are used for the code
  breakatwhitespace=false,         % sets if automatic breaks should only happen at whitespace
  breaklines=true}
\section{timer.h}
\label{source:timer}
\lstinputlisting[language=c]{../main/timer.h}
\section{adc.h}
\label{source:adc}
\lstinputlisting[language=c]{../main/adc.h}
\section{lcd.h}
\label{source:lcd}
\lstinputlisting[language=c]{../main/lcd.h}
\section{pid.h}
\label{source:pid}
\lstinputlisting[language=c]{../main/pid.h}
\section{motor.h}
\label{source:motors}
\lstinputlisting[language=c]{../main/motor.h}
\section{configuration.h}
\label{source:config}
\lstinputlisting[language=c]{../main/configuration.h}
\section{eventDetection.h}
\label{source:eventDetection}
\lstinputlisting[language=c]{../main/eventDetection.h}
\section{main.c}
\label{source:main}
\lstinputlisting[language=c]{../main/main.c}
\end{document}
